<?php
namespace app\api\controller;
use app\common\controller\BaseApi;

/**
 * 定时任务
 * */
class Timer extends  BaseApi
{
	function _initialize() {
    }
	/*
	 * http://smartgym.com/api/Timer/DoLessonDown??sk=27615e64890e433c74e9eb34f974abc
	 * */
	function DoLessonDown(){
		if(input('sk','')!='27615e64890e433c74e9eb34f974abc'){
			var_dump("no auth");die;
		}
		//找出所有没有启动的任务
		$list=db("AutoLessonEnd")->field("id,employee_id,member_id,reservation_id,number,shop_id,will_excute_time")->where("start_status=1 and will_excute_time<DATE_FORMAT(NOW(),'%Y-%m-%d %H:%i:%s') ")->select();
		foreach ($list as $key => $value) {
			$config=$this->_GetConfig($value['shop_id'],$value['id']);
			if($config==FALSE){
				continue;
			}
			try{
				$res= post_submit_xml(
		 							"http://host.gymparty.net:81/CSmart/SCHWebService.asmx/DoLessonEnd",
		 							array(
		 								  "BrandCode"=>$config['BrandCode'],
		 								  "ClubId"=>$config['ClubID'],
		 								  "Key"=>$config['Key'],
		 								  "EmployeeID"=>$value['employee_id'],
		 								  "MemberID"=>$value['member_id'],
		 								  "ReservationID"=>$value['reservation_id'],
		 								  "Number"=>$value['number'],
										  )
										);
			}catch(\Exception $e){
				db("AutoLessonEnd")->where("id=".$value['id'])->setField(array("start_status"=>2,"result_status"=>3,"api_result"=>$e->getCode(),"api_descs"=>$e->getMessage(),"over_excute_time"=>date("Y-m-d H:i:s")));
				continue;
			}							  
			if(empty($res)){
				db("AutoLessonEnd")->where("id=".$value['id'])->setField(array("start_status"=>2,"result_status"=>3,"api_descs"=>"配置错误或者参数错误","over_excute_time"=>date("Y-m-d H:i:s")));
			}else{
				$res=json_decode($res[0],TRUE);
				if($res["Status"]==1){
					db("AutoLessonEnd")->where("id=".$value['id'])->setField(array("start_status"=>2,"result_status"=>2,"api_result"=>$res["Remark"],"api_descs"=>"下课成功","over_excute_time"=>date("Y-m-d H:i:s")));
				}else{
					db("AutoLessonEnd")->where("id=".$value['id'])->setField(array("start_status"=>2,"result_status"=>3,"api_result"=>$res["Remark"],"api_descs"=>"下课失败","over_excute_time"=>date("Y-m-d H:i:s")));	
				}
				
			}
		}
			var_dump("over");die;
	}
	/**
	 * 查询图片是否存在
	 * http://smartgym.com/api/Timer/CheckImgToday?sk=27615e64890e433c74e9eb34f974abc&page=0
	 * */
	function CheckImgToday(){
		$page=input('page/d',0);
		if(input('sk','')!='27615e64890e433c74e9eb34f974abc'){
			var_dump("no auth,page:".$page);die;
		}
		
		$list=db("FlatVarifyRecord")->field("id,image_url")->limit($page*500,500)->order("id desc")->where("type=1 and TO_DAYS(create_time)=TO_DAYs(NOW())")->select();
		$error=$this->_check_remote_file_exists($list);
		foreach ($error as $k => $v) {
			if(!empty($v)){
				$record=db("FlatVarifyRecord")->field("id as record_id,shop_id,member_name,pt_name,pt_mobile,member_mobile,image_url")->find($v);
				$count=db("ErrorImg")->where("record_id=".$record['record_id'])->count(1);
				if(empty($count)){
					db("ErrorImg")->insert($record);	
				}	
			}
		}
		$error=json_encode($error);
		var_dump("page:".$page.",record_id:".$error);die;
	}
	//////////////////////////////////////////////////////////////////////////////////////////
	/**
	 * 检测图片是否存在
	 * */
	function _check_remote_file_exists($list)
	{
		$error=[];
		if(empty($list)){
			var_dump("没有记录");die;
		}
		$curl = curl_init();
		foreach ($list as $key => $value) {
			$images=explode(",", $value['image_url']);
			foreach ($images as $kk => $vv) {
				if(!empty($vv)){
					try{
						$result=get_headers($vv, 1);						
					}catch(\Exception $e){
						$error[]=$value['id'];
						break;
					}
					// 如果请求没有发送失败
					if (!preg_match('/200/',$result[0]))
					{
						$error[]=$value['id'];
						break;
					}						
				}else{
					$error[]=$value['id'];
				}
			}
		}
		return $error;
	}
	private function _GetConfig($shop_id,$auto_id){
		$config_shopinfo=cache("ShopInfo_".$shop_id);
		if(empty($config_shopinfo)){
			$config_shopinfo=db("Shop")->where("id=".$shop_id)->find();
			if(empty($config_shopinfo)){
				db("AutoLessonEnd")->where("id=".$auto_id)->setField(array("start_status"=>2,"result_status"=>3,"api_descs"=>"店铺id 不存在","over_excute_time"=>date("Y-m-d H:i:s")));
				return FALSE;
			}else{
				cache("ShopInfo_".$shop_id,$config_shopinfo);
			}
		}
		if($config_shopinfo['api_version']=='anke'){// 安科系统
			$config=cache("ExtraConfig_".$shop_id);
	    	if(empty($config)){
				 $config=db("Shop")->where("id=".$shop_id." and api_version='anke'")->value("extra_config");
				 if(empty($config)){
				 	db("AutoLessonEnd")->where("id=".$auto_id)->setField(array("start_status"=>2,"result_status"=>3,"api_descs"=>"店铺id配置错误,或者安科配置代码错误","over_excute_time"=>date("Y-m-d H:i:s")));
					return FALSE;
				}
				 $config=json_decode($config,TRUE);
				 cache("ExtraConfig_".$shop_id,$config);
	    	} 
			if(!isset($config['BrandCode'])){
				db("AutoLessonEnd")->where("id=".$auto_id)->setField(array("start_status"=>2,"result_status"=>3,"api_descs"=>"无效的安科配置代码","over_excute_time"=>date("Y-m-d H:i:s")));
				return FALSE;
			}
			return $config;
		}else{
			db("AutoLessonEnd")->where("id=".$auto_id)->setField(array("start_status"=>2,"result_status"=>3,"api_descs"=>"不是安科系统，不能执行自动下课任务","over_excute_time"=>date("Y-m-d H:i:s")));
			return FALSE;
		}
		
	}
}
